using EnvDTE;
using Microsoft.Practices.RecipeFramework;
using VSSDKAssist.Assets.Actions.Base;
using VSSDKAssist.Assets.Helpers;

namespace VSSDKAssist.Assets.Actions.VisualStudio
{
	/// <summary>
	/// Action that adds a folder to a Project item
	/// </summary>
    public class AddProjectFolderToProjectItemAction : ActionBase
	{
		#region Fields
        /// <summary>
        /// Gets or sets the name of the folder.
        /// </summary>
        /// <value>The name of the folder.</value>
        [Input(Required = true)]
        public string FolderName { get; set; }

        /// <summary>
        /// Gets or sets the projectitem.
        /// </summary>
        /// <value>The projectitem.</value>
        [Input(Required = true)]
        public ProjectItem ProjectItem { get; set; }

		private ProjectItem folderAdded;

		/// <summary>
		/// Gets or sets the folder added.
		/// </summary>
		/// <value>The folder added.</value>
		[Output]
		public ProjectItem FolderAdded
		{
			get { return folderAdded; }
			set { folderAdded = value; }
		}
		#endregion

		#region Protected Implementation
		/// <summary>
		/// Called when [execute].
		/// </summary>
		protected override void OnExecute()
		{
			string[] foldersArray = this.FolderName.Split('\\');

			if(foldersArray.Length > 0)
			{
				ProjectItem lastItem = VSIPHelper.FindItemByName(this.ProjectItem.ContainingProject.ProjectItems, foldersArray[0], false);

				if(lastItem == null)
				{
					lastItem = AddFolder(this.ProjectItem.ProjectItems, foldersArray[0]);

					for(int i = 1; i < foldersArray.Length; i++)
					{
						lastItem = AddFolder(lastItem.ProjectItems, foldersArray[i]);
					}
				}
				else
				{
					for(int i = 1; i < foldersArray.Length; i++)
					{
						ProjectItem itemTemp = VSIPHelper.FindItemByName(lastItem.ProjectItems, foldersArray[i], false);

						if(itemTemp == null)
						{
							lastItem = AddFolder(lastItem.ProjectItems, foldersArray[i]);
						}
						else
						{
							lastItem = itemTemp;
						}
					}
				}

				folderAdded = lastItem;
			}
		} 
		#endregion

		#region Private Implementation
		private static ProjectItem AddFolder(ProjectItems items, string folder)
		{
			return items.AddFolder(folder, EnvDTE.Constants.vsProjectItemKindPhysicalFolder);
		} 
		#endregion
	}
}